<template>
  <div>
    <el-card class="mineSwp-container" shadow="hover" :body-style="{ padding: '20px' }">
      <div slot="header" class="card-header">
        <div>
          <el-button type="success" v-if="isGaming" plain @click="reStart">重新开始</el-button>
          <el-button type="success" v-else plain @click="startGame">开始游戏</el-button>
        </div>
      </div>
      <!-- card body -->
      <div class="content1" v-if="blocks.length==16">
        <div v-for="(item, index) in blocks" :key="index">{{item.num}}</div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 是否开始游戏
      isGaming: false,

      // 方块
      blocks: [],
    };
  },

  created() {
    // 组件内监听 上、下、左、右键
    document.onkeydown = () => {
      let key = window.event.keyCode;
      if (key == 37) {
        this.blkMove("l");
      } else if (key == 38) {
        this.blkMove("u");
      } else if (key == 39) {
        this.blkMove("r");
      } else if (key == 40) {
        this.blkMove("d");
      }
    };
  },
  methods: {
    /**
     * 下标对应的方块
     *  0   1   2   3
     *  4   5   6   7
     *  8   9   10  11
     *  12  13  14  15
     */
    init() {
      // 数据初始化
      this.isGaming = false;
      this.blocks = [];

      for (let i = 0; i < 16; i++) {
        this.blocks.push({
          num: "",
        });
      }
      this.blocks[0].num = 2;
    },

    startGame() {
      this.init();
      this.isGaming = true;
    },

    // 重新开始按钮
    reStart() {
      this.init();
    },

    // 方块移动方法
    blkMove(direction) {
      if (direction == "l") {
        console.log("keyLeft");
      } else if (direction == "r") {
        console.log("keyRight");
      } else if (direction == "u") {
        console.log("keyUp");
      } else if (direction == "d") {
        console.log("keyDown");
      }
    },
  },
};
</script>

<style scoped>
.mineSwp-container {
  width: 100%;
  background-color: #fffaf0;
  height: 86vh;
}

.card-header {
  display: flex;
}

.content1 {
  width: 500px;
  height: 500px;
  margin: 0 auto;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin-top: 40px;
}

.content1 > div {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0px 0px 10px rgb(39, 39, 39);
  margin-left: 1px;
  margin-right: 1px;
}
</style>